package com.liyuxiang.yygh.oss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.liyuxiang.yygh.oss.service.FileService;
import com.liyuxiang.yygh.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String fileUpload(MultipartFile file) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ConstantPropertiesUtils.ENDPOINT, ConstantPropertiesUtils.ACCESS_KEY_ID, ConstantPropertiesUtils.SECRET);

        try {
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            if (fileName.lastIndexOf(".") != -1) {
                fileName = UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));
            }
            //按照当前日期，创建文件夹，上传到创建的文件夹里面
            String filePath = new DateTime().toString("yyyy/MM/dd");
            // 创建PutObject请求。
            ossClient.putObject(ConstantPropertiesUtils.BUCKET_NAME, filePath + "/" + fileName, inputStream);
            String url = "https://" + ConstantPropertiesUtils.BUCKET_NAME + "." + ConstantPropertiesUtils.ENDPOINT + "/" + filePath + "/" + fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
